package com.zjx.mhxykey.util;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Build;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.ScrollView;

import androidx.annotation.RequiresApi;

/**
 * 屏幕截图工具类
 * 提供多种截图功能，包括指定范围截图、View截图、ScrollView完整截图等
 */
public class ScreenshotUtils {
    private static final String TAG = "ScreenshotUtils";

    /**
     * 截取指定View的可见部分
     *
     * @param view 要截图的View
     * @return 截图Bitmap，如果失败返回null
     */
    public static Bitmap captureView(View view) {
        if (view == null) {
            Log.w(TAG, "captureView: 输入view为null");
            return null;
        }

        try {
            Bitmap bitmap = Bitmap.createBitmap(
                    view.getWidth(),
                    view.getHeight(),
                    Bitmap.Config.ARGB_8888
            );
            Canvas canvas = new Canvas(bitmap);
            view.draw(canvas);
            return bitmap;
        } catch (Exception e) {
            Log.e(TAG, "captureView: 截图失败", e);
            return null;
        }
    }

    /**
     * 截取View的指定区域
     *
     * @param view 要截图的View
     * @param rect 要截取的区域（相对于View的坐标）
     * @return 截图Bitmap，如果失败返回null
     */
    public static Bitmap captureViewArea(View view, Rect rect) {
        if (view == null || rect == null) {
            Log.w(TAG, "captureViewArea: 输入参数为null");
            return null;
        }

        try {
            // 确保区域在View范围内
            Rect validRect = new Rect(
                    Math.max(0, rect.left),
                    Math.max(0, rect.top),
                    Math.min(view.getWidth(), rect.right),
                    Math.min(view.getHeight(), rect.bottom)
            );

            if (validRect.width() <= 0 || validRect.height() <= 0) {
                Log.w(TAG, "captureViewArea: 无效的截图区域");
                return null;
            }

            Bitmap fullBitmap = captureView(view);
            if (fullBitmap == null) {
                return null;
            }

            return Bitmap.createBitmap(
                    fullBitmap,
                    validRect.left,
                    validRect.top,
                    validRect.width(),
                    validRect.height()
            );
        } catch (Exception e) {
            Log.e(TAG, "captureViewArea: 区域截图失败", e);
            return null;
        }
    }

    /**
     * 截取整个ScrollView的内容（包括未显示部分）
     *
     * @param scrollView 要截图的ScrollView
     * @return 完整内容截图Bitmap，如果失败返回null
     */
    public static Bitmap captureScrollView(ScrollView scrollView) {
        if (scrollView == null) {
            Log.w(TAG, "captureScrollView: 输入scrollView为null");
            return null;
        }

        try {
            View child = scrollView.getChildAt(0);
            if (child == null) {
                return null;
            }

            // 保存原始高度
            int originalHeight = child.getHeight();

            // 测量子View的完整高度
            child.measure(
                    View.MeasureSpec.makeMeasureSpec(scrollView.getWidth(), View.MeasureSpec.EXACTLY),
                    View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
            );
            int measuredHeight = child.getMeasuredHeight();

            // 临时设置高度以渲染完整内容
            ViewGroup.LayoutParams lp = child.getLayoutParams();
            lp.height = measuredHeight;
            child.setLayoutParams(lp);

            Bitmap bitmap = Bitmap.createBitmap(
                    child.getWidth(),
                    measuredHeight,
                    Bitmap.Config.ARGB_8888
            );
            Canvas canvas = new Canvas(bitmap);
            child.draw(canvas);

            // 恢复原始高度
            lp.height = originalHeight;
            child.setLayoutParams(lp);

            return bitmap;
        } catch (Exception e) {
            Log.e(TAG, "captureScrollView: 截图失败", e);
            return null;
        }
    }

    /**
     * 截取屏幕的指定区域（需要API级别>=21）
     *
     * @param activity 当前Activity
     * @param rect 要截取的区域（屏幕绝对坐标）
     * @return 截图Bitmap，如果失败返回null
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public static Bitmap captureScreenArea(Activity activity, Rect rect) {
        if (activity == null || rect == null) {
            Log.w(TAG, "captureScreenArea: 输入参数为null");
            return null;
        }

        try {
            View decorView = activity.getWindow().getDecorView();
            Bitmap fullBitmap = captureView(decorView);
            if (fullBitmap == null) {
                return null;
            }

            // 确保区域在屏幕范围内
            Rect validRect = new Rect(
                    Math.max(0, rect.left),
                    Math.max(0, rect.top),
                    Math.min(fullBitmap.getWidth(), rect.right),
                    Math.min(fullBitmap.getHeight(), rect.bottom)
            );

            return Bitmap.createBitmap(
                    fullBitmap,
                    validRect.left,
                    validRect.top,
                    validRect.width(),
                    validRect.height()
            );
        } catch (Exception e) {
            Log.e(TAG, "captureScreenArea: 屏幕区域截图失败", e);
            return null;
        }
    }

    /**
     * 截取WebView的指定区域（需要WebView已加载完成）
     *
     * @param webView 要截图的WebView
     * @param rect 要截取的区域（WebView内容坐标）
     * @return 截图Bitmap，如果失败返回null
     */
    public static Bitmap captureWebViewArea(WebView webView, Rect rect) {
        if (webView == null || rect == null) {
            Log.w(TAG, "captureWebViewArea: 输入参数为null");
            return null;
        }

        try {
            // 获取WebView内容的总高度
            int contentHeight = (int) (webView.getContentHeight() * webView.getScale());

            // 确保区域在WebView内容范围内
            Rect validRect = new Rect(
                    Math.max(0, rect.left),
                    Math.max(0, rect.top),
                    Math.min((int) webView.getWidth(), rect.right),
                    Math.min(contentHeight, rect.bottom)
            );

            if (validRect.width() <= 0 || validRect.height() <= 0) {
                Log.w(TAG, "captureWebViewArea: 无效的截图区域");
                return null;
            }

            // 创建完整内容bitmap
            Bitmap fullBitmap = Bitmap.createBitmap(
                    webView.getWidth(),
                    contentHeight,
                    Bitmap.Config.ARGB_8888
            );
            Canvas canvas = new Canvas(fullBitmap);
            webView.draw(canvas);

            // 截取指定区域
            return Bitmap.createBitmap(
                    fullBitmap,
                    validRect.left,
                    validRect.top,
                    validRect.width(),
                    validRect.height()
            );
        } catch (Exception e) {
            Log.e(TAG, "captureWebViewArea: WebView截图失败", e);
            return null;
        }
    }

    public static void main(String[] args) {
        View myView = null;
        ScrollView myScrollView = null;
        Activity MainActivity = null;
        WebView myWebView = null;

        // 1. 截取整个View
        Bitmap viewBitmap = ScreenshotUtils.captureView(myView);

// 2. 截取View的指定区域
        Rect area = new Rect(100, 200, 500, 600); // left, top, right, bottom
        Bitmap areaBitmap = ScreenshotUtils.captureViewArea(myView, area);

// 3. 截取整个ScrollView内容
        Bitmap scrollBitmap = ScreenshotUtils.captureScrollView(myScrollView);

// 4. 截取屏幕指定区域（API >= 21）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Rect screenArea = new Rect(50, 100, 300, 400);
            Bitmap screenBitmap = ScreenshotUtils.captureScreenArea(MainActivity, screenArea);
        }

// 5. 截取WebView指定区域
        Bitmap webBitmap = ScreenshotUtils.captureWebViewArea(myWebView, new Rect(0, 0, 500, 800));


        //注意
//        内存管理：大尺寸截图可能消耗大量内存，使用后应及时回收Bitmap
//        if (!bitmap.isRecycled()) {
//            bitmap.recycle();
//        }
//        权限要求：截取屏幕可能需要特殊权限
//         <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    }
}